package org.gten.gegedexin.service.user.interception;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.gten.gegedexin.service.TokenServiceImpl;
import org.gten.gegedexin.service.user.common.ResResult;
import org.gten.gegedexin.service.user.constant.Constant;
import org.gten.gegedexin.service.user.common.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Component
public class LoginInterception implements HandlerInterceptor {

    static TokenServiceImpl mTokenService;

    @Autowired
    public void setTokenService(TokenServiceImpl tokenService){
        mTokenService = tokenService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod().toUpperCase())){
            System.out.println(LocalDateTime.now()+":"+"[登录拦截器]OPTION请求");
            return true;
        }
        String token = request.getHeader(Constant.TOKEN_HEADER_NAME.getClaim());
        if(StringUtils.isBlank(token)){
            returnNoLogin(response);
            System.out.println(LocalDateTime.now()+":"+"[登录拦截器]未登录访问（已拦截）");
            return false;
        }

        System.out.println(mTokenService == null);
        mTokenService.judgeOutOfTime(token);
        String account = mTokenService.getAccount(token);

        if(account==null){
            returnNoLogin(response);
            System.out.println(LocalDateTime.now()+":"+"[登录拦截器]未登录访问（已拦截）");
            return false;
        }

        mTokenService.updateTime(token);
        System.out.println(LocalDateTime.now()+":"+"[登录拦截器]"+account+"发送了一条请求");
        return true;
    }

    public void returnNoLogin(HttpServletResponse response)throws IOException {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setStatus(401);
        response.setContentType("Application/json;charset=utf-8");
        String resultString = JSONObject.toJSONString(ResResult.fail(ResultCode.NO_LOGIN));
        servletOutputStream.write(resultString.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
